const bcrypt = require('bcryptjs');
const db = require('../config/database');

async function createAdmin() {
    try {
        // 创建管理员账号数据
        const adminData = {
            admin_name: '系统管理员',
            email: 'admin@example.com',
            password: 'admin123',
            role: 'super_admin'
        };

        // 生成密码哈希
        const hashedPassword = await bcrypt.hash(adminData.password, 10);

        // 检查表是否存在，如果不存在则创建
        await db.execute(`
            CREATE TABLE IF NOT EXISTS admins (
                admin_id INT AUTO_INCREMENT PRIMARY KEY,
                admin_name VARCHAR(50) NOT NULL,
                email VARCHAR(100) NOT NULL UNIQUE,
                password VARCHAR(255) NOT NULL,
                role ENUM('admin', 'super_admin') NOT NULL DEFAULT 'admin',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            )
        `);

        // 检查是否已存在相同邮箱的管理员
        const [existingAdmin] = await db.execute('SELECT * FROM admins WHERE email = ?', [adminData.email]);
        
        if (existingAdmin.length > 0) {
            // 如果存在，更新密码
            await db.execute(
                'UPDATE admins SET password = ? WHERE email = ?',
                [hashedPassword, adminData.email]
            );
            console.log('管理员密码已更新');
        } else {
            // 如果不存在，创建新管理员
            await db.execute(
                'INSERT INTO admins (admin_name, email, password, role) VALUES (?, ?, ?, ?)',
                [adminData.admin_name, adminData.email, hashedPassword, adminData.role]
            );
            console.log('管理员账号已创建');
        }

        console.log('管理员账号信息：');
        console.log('邮箱:', adminData.email);
        console.log('密码:', adminData.password);
        
        process.exit(0);
    } catch (error) {
        console.error('创建管理员账号时出错:', error);
        process.exit(1);
    }
}

createAdmin(); 